package com.lindroy.androidplayer.ui.login

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.viewModels
import com.google.gson.Gson
import com.lindroid.androidutilskt.statics.AppManager
import com.lindroy.androidplayer.MainActivity
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.base.BaseFragment
import com.lindroy.androidplayer.base.BaseLazyFragment
import com.lindroy.androidplayer.base.appViewModel
import com.lindroy.androidplayer.constants.SP_KEY_LOGIN_INFO
import com.lindroy.androidplayer.extensions.parseState
import com.lindroy.androidplayer.extensions.setInputLetterSpacing
import com.lindroy.lib_utils.extensions.isTextEmpty
import com.lindroy.lib_utils.extensions.putSpString
import com.lindroy.lib_utils.extensions.shortToast
import com.lindroy.lib_utils.extensions.textString
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.android.synthetic.main.fragment_login.etName
import kotlinx.android.synthetic.main.fragment_login.etPwd


/**
 * @author Lin
 * @date 2021/4/15
 * @function 登录
 * @Description
 */
class LoginFragment(override val layoutId: Int = R.layout.fragment_login) : BaseLazyFragment() {

    private var listener: OnRegisterClickListener? = null

    private val loginViewModel: LoginViewModel by viewModels()

    override fun onAttach(context: Context) {
        super.onAttach(context)
        listener = context as? OnRegisterClickListener
    }

    override fun initView() {
        addLoadingObserve(loginViewModel)
        etPwd.setInputLetterSpacing()

    }

    override fun lazyLoad() {
        loginViewModel.loginResult.observe(this) { resultState ->
            parseState(resultState, onError = {
                shortToast(it.errorMsg)
            }) {
                putSpString(SP_KEY_LOGIN_INFO, Gson().toJson(it))
                appViewModel.loginInfo.value = it
                AppManager.finishAllActivity()
                context?.let {ctx-> MainActivity.start(ctx) }
            }
        }

    }


    override fun initListener() {

        tvRegister.setOnClickListener {
            listener?.onRegisterClick()

        }
        btnLogin.setOnClickListener {
            login()
        }
    }

    override fun initClick() {

    }

    private fun login() {
        if (etName.isTextEmpty) {
            shortToast("用户名不能为空")
            return
        }
        if (etPwd.isTextEmpty) {
            shortToast("密码不能为空")
            return
        }
        loginViewModel.login(etName.textString, etPwd.textString)
    }

    companion object {
        @JvmStatic
        fun newInstance() =
            LoginFragment().apply {
                arguments = Bundle().apply {
                }
            }
    }

    interface OnRegisterClickListener {
        fun onRegisterClick()
    }
}